package com.atguigu.url.util;

import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @version V1.0
 * @author: guangcheng
 * @date: 2021/11/15 22:08
 * @description:
 */
@Component
public class MD5DigestUtil {


    /**
     * 获取字符串MD5摘要
     *
     * @param message
     * @return
     */
    public String getMD5(String message) {

        try {

            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] b = md5.digest(message.getBytes("utf-8"));

            return byteToHexStringSingle(b);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return "";
    }


    char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public String byteToHexStringSingle(byte[] bytes) {
        StringBuffer md5sb = new StringBuffer();

        for (int i = 0; i < bytes.length; i++) {
            if (Integer.toHexString(0xFF & bytes[i]).length() == 1) {
                md5sb.append("0").append(Integer.toHexString(0xFF & bytes[i]));
            } else {
                md5sb.append(Integer.toHexString(0xFF & bytes[i]));
            }
        }

        return md5sb.toString();
    }


    public String byteToHexString(byte[] tmp) {
        String s = "";
        char[] str = new char[16 * 2];
        int k = 0;
        for (int i = 0; i < 16; i++) {
            byte byte0 = tmp[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }

        s = new String(str);
        return s;
    }


}

